<template>
    <div>
        <!--新增-->
        <el-form :inline="true" :model="addForm" style="margin: 10px">
            <el-form-item>
                <el-button type="primary" @click="addVisible= true" style="margin-top: 10px" >新增</el-button>
                <el-button type="primary" @click="addBatchVisible= true" style="margin-top: 10px" >批量新增</el-button>
            </el-form-item>
        </el-form>

        <!--成员表格-->
        <el-table title="成员列表"
                  ref="MemberTable"
                  :data="tableData"
                  border
                  stripe
                  style="width: fit-content; margin-left: 10px">
            <el-table-column
                    prop="userRole"
                    label="身份"
                    width="80">
            </el-table-column>
            <el-table-column
                    prop="username"
                    label="学号/工号"
                    width="120">
            </el-table-column>
            <el-table-column
                    prop="name"
                    label="姓名"
                    width="80">
            </el-table-column>
            <el-table-column
                    prop="identificationNumber"
                    label="身份证号"
                    width="180">
            </el-table-column>
            <el-table-column
                    prop="phoneNumber"
                    label="手机号"
                    width="150">
            </el-table-column>
            <el-table-column
                    prop="email"
                    label="邮箱"
                    width="220">
            </el-table-column>
            <el-table-column
                    prop="collegeName"
                    label="院系"
                    width="140">
            </el-table-column>
            <el-table-column
                    prop="majorName"
                    label="专业"
                    width="160">
            </el-table-column>
            <el-table-column
                    prop="statu"
                    label="状态"
                    width="120">
            </el-table-column>
            <el-table-column
                    fixed="right"
                    label="操作"
                    width="100">
                <template slot-scope="scope">
                    <el-button @click="editHandle(scope.row.username)" type="text" size="small">编辑</el-button>
                    <el-divider direction="vertical"></el-divider>
                    <el-popconfirm title="没办法啦后端没写这个接口" @confirm="delHandle(scope.row.username)" >
                        <el-button type="text" slot="reference">删除</el-button>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>

        <!--新增成员对话框-->
        <el-dialog title="请输入新增成员信息" :visible.sync="addVisible" width="600px" @closed="resetAddForm('addForm')">

            <el-form :model="addForm" :rules="addFormRules" ref="addForm">
                <el-form-item label="身份" prop="userRole" label-width="100px">
                    <el-select v-model="addForm.userRole" placeholder="请选择">
                        <el-option
                                v-for="item in roleOp"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="身份证号" prop="identificationNumber" label-width="100px">
                    <el-input v-model="addForm.identificationNumber" autocomplete="off"
                              maxlength="18"
                              show-word-limit
                    >
                    </el-input>
                </el-form-item>
                <el-form-item label="姓名" prop="name" label-width="100px">
                    <el-input v-model="addForm.name" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="学号/工号" prop="username" label-width="100px">
                    <el-input v-model="addForm.username" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="院系" prop="college" label-width="100px">
                    <el-select v-model="addForm.college" placeholder="请选择院系" clearable filterable
                               @change="getMajorByCollege(addForm.college);">
                        <el-option
                                v-for="item in collegeData"
                                :key="item.id"
                                :label="item.college"
                                :value="item.id"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="专业" prop="major" label-width="100px">
                    <el-select v-model="addForm.major" placeholder="请选择" clearable filterable>
                        <el-option
                                v-for="item in majorData"
                                :key="item.id"
                                :label="item.major"
                                :value="item.id"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="状态" prop="statu" label-width="100px" >
                  <el-radio-group v-model="addForm.statu">
                    <el-radio v-for="item in statuOp"
                              :key="item.value"
                              :label="item.label"
                    ></el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="密码" prop="password" label-width="100px">
                    <el-input v-model="addForm.password" readonly disabled placeholder="123456"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="phoneNumber" label-width="100px">
                    <el-input v-model="addForm.phoneNumber" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email" label-width="100px">
                    <el-input v-model="addForm.email" autocomplete="off"></el-input>
                </el-form-item>

            </el-form>
            <!--按钮-->
            <div slot="footer" class="dialog-footer">
                <el-button @click="resetAddForm('addForm')">取 消</el-button>
                <el-button type="primary" @click="submitAddForm('addForm')">提交</el-button>
            </div>
        </el-dialog>

        <!--批量新增成员对话框-->
        <el-dialog title="请选择批量新增人员的文件" :visible.sync="addBatchVisible" width="600px" @closed="resetForm('moreForm')">
            <!--            <el-form :model="moreForm" :rules="moreFormRules" ref="moreForm">-->
            <!--                <el-form-item label="" prop="filename" label-width="120px">-->
            <!--                    <el-upload-->
            <!--                            class="upload-demo"-->
            <!--                            accept=".csv"-->
            <!--                            action=""-->
            <!--                            :on-preview="handlePreview"-->
            <!--                            :file-list="fileList"-->
            <!--                            :http-request="beforeUpload"-->
            <!--                            :limit="1"-->

            <!--                            :on-exceed="handleExceed"-->
            <!--                            :on-remove="handleRemove"-->
            <!--                            :before-remove="beforeRemove"-->
            <!--                            :auto-upload="false"-->
            <!--                    >-->

            <!--                        &lt;!&ndash;&lt;!&ndash;              :headers="{'Authorization':userInfo.token}"&ndash;&gt;&ndash;&gt;-->
            <!--                        &lt;!&ndash;&lt;!&ndash;              :http-request="beforeUpload"&ndash;&gt;&ndash;&gt;-->
            <!--                        &lt;!&ndash;&lt;!&ndash;              :before-upload="before_Upload"&ndash;&gt;&ndash;&gt;-->
            <!--                        &lt;!&ndash;&lt;!&ndash;              :file-list="fileList"&ndash;&gt;&ndash;&gt;-->
            <!--                        &lt;!&ndash;&lt;!&ndash;              :on-success="upSuccess"&ndash;&gt;&ndash;&gt;-->
            <!--                        &lt;!&ndash;&lt;!&ndash;              :on-error="upError"&ndash;&gt;&ndash;&gt;-->
            <!--                        <div slot="tip" class="el-upload__tip">只能上传csv文件，且不超过500kb</div>-->
            <!--                        <el-button size="small" type="primary">点击上传</el-button>-->
            <!--                    </el-upload>-->
            <!--                </el-form-item>-->
            <!--            </el-form>-->
            <!--        <div slot="footer" class="dialog-footer">-->
            <!--            <el-button @click="resetForm('moreForm')">取 消</el-button>-->
            <!--            <el-button type="primary" @click="beforeUpload('moreForm')">提交</el-button>-->
            <!--        </div>-->
            <input type="file" accept=".csv" @change="importcsv"/>
        </el-dialog>

        <!--编辑成员对话框-->
        <el-dialog title="编辑人员信息" :visible.sync="editVisible" width="600px" @closed="resetForm('editForm')">
            <el-form :model="editForm" :rules="editFormRules" ref="editForm">
                <el-form-item label="身份" prop="userRole" label-width="100px">
                    <el-select v-model="editForm.userRole" placeholder="请选择" disabled>
                        <el-option
                                v-for="item in roleOp"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="身份证号" prop="identificationNumber" label-width="100px">
                    <el-input v-model="editForm.identificationNumber" autocomplete="off"
                              maxlength="18"
                              show-word-limit
                    >
                    </el-input>
                </el-form-item>
                <el-form-item label="姓名" prop="name" label-width="100px">
                    <el-input v-model="editForm.name" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="学号/工号" prop="username" label-width="100px">
                    <el-input v-model="editForm.username" readonly disabled></el-input>
                </el-form-item>
                <el-form-item label="状态" prop="statu" label-width="100px" >
                  <el-radio-group v-model="editForm.statu">
                    <el-radio v-for="item in statuOp"
                              :key="item.value"
                              :label="item.label"
                    ></el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="院系" prop="college" label-width="100px">
                    <el-select v-model="editForm.college" placeholder="请选择院系" clearable filterable
                               @change="getMajorByCollege(editForm.college)">
                        <el-option
                                v-for="item in collegeData"
                                :key="item.id"
                                :label="item.college"
                                :value="item.id"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="专业" prop="major" label-width="100px">
                    <el-select v-model="editForm.major" placeholder="请选择" clearable filterable>
                        <el-option
                                v-for="item in majorData"
                                :key="item.id"
                                :label="item.major"
                                :value="item.id"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="手机号" prop="phoneNumber" label-width="100px">
                    <el-input v-model="editForm.phoneNumber" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email" label-width="100px">
                    <el-input v-model="editForm.email" autocomplete="off"></el-input>
                </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="resetEditForm('editForm')">取 消</el-button>
                <el-button type="primary" @click="submitEditForm('editForm')">确 定</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
    import qs from 'qs'
    import store from '@/store'
    import papa from 'papaparse';

    export default {
        name: "Members",
        data() {
            //学工号长度校验
            var validateUserId = (addFormRules,value,callback)=>{
                let ROLE = this.addForm.userRole;
                if(ROLE === "学生") {
                    if(value.length !== 6){
                        callback(new Error("学生学号6位"));
                    }
                    else{
                        callback();
                    }
                    // //转义符版本
                    // /^\d{6}$/.test(value)
                    //     ?callback()
                    //     :callback(new Error("学生学号6位"));
                }
                else if(ROLE === "教师") {
                    if(value.length !== 8){
                        callback(new Error("教师工号8位"));
                    }
                    else{
                        callback();
                    }
                    // /^\d{8}$/.test(value)
                    //     ?callback()
                    //     :callback(new Error("教师工号8位"));
                }
                else{
                    callback();
                }
            };
            // Papa.parse(file, {
            //     complete: function(results) {
            //         console.log(results);//返回的csv的数据
            //     }
            // });


            return {
                //表格数据
                tableData: [],
                //院系专业数据
                collegeData: [],
                //专业数据
                majorData: [],
                //提交表单的身份选项
                roleOp: [
                    {
                        value: '教师',
                        label: '教师'
                    },
                    {
                        value: '学生',
                        label: '学生'
                    }
                ],

                //新增成员表单
                addForm: {
                  statu:"在读/在职"
                },
                statuOp:[
                  {label:"在读/在职",value:"在读/在职"},
                  {label:"毕业/离职",value:"毕业/离职"}
                ],

                //提交新增成员表单规则
                addFormRules: {
                    userRole: [
                        {required: true, message: '请选择身份', trigger: 'blur'}
                    ],
                    identificationNumber: [
                        {required: true, message: '请输入身份证号', trigger: 'blur'},
                        {pattern:/^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,message: "身份证号码格式不正确",trigger:"blur"}
                    ],
                    name: [
                        {required: true, message: '请输入姓名', trigger: 'blur'},
                        {pattern:/^([\u4E00-\uFA29]*[a-z]*[A-Z]*)+$/,message: "姓名只能出现中文或英文字符",trigger:"blur"}
                    ],
                    username: [
                        {required: true, message: '请输入学号/工号', trigger: 'blur'},
                        {validator:validateUserId, trigger:"blur"},
                        // {min:6, max:8, message:"长度应为6-8个数字",trigger: 'blur'},
                    ],
                    phoneNumber: [
                        {required: false, message: '请输入手机号', trigger: 'blur'},
                        { pattern: /^1[3456789]\d{9}$/, message: "手机号码格式不正确", trigger: "blur" }
                    ],
                    email: [
                        {required: false,message: '请输入邮箱', trigger: 'blur'},
                        { pattern: /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/,message:"邮箱格式不正确",trigger:"blur"}
                    ],
                    statu: [
                        {required: false, message: '请选择状态', trigger: 'blur'}
                    ],
                },

                //编辑成员表单
                editForm:{},
                //编辑成员表单规则
                editFormRules:{
                    userRole: [
                        {required: true, message: '请选择身份', trigger: 'blur'}
                    ],
                    identificationNumber: [
                        {required: true, message: '请输入身份证号', trigger: 'blur'},
                        {pattern:/^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,message: "身份证号码格式不正确",trigger:"blur"}
                    ],
                    name: [
                        {required: true, message: '请输入姓名', trigger: 'blur'},
                        {pattern:/^([\u4E00-\uFA29]*[a-z]*[A-Z]*)+$/,message: "姓名只能出现中文或英文字符",trigger:"blur"}
                    ],
                    username: [
                        {required: true, message: '请输入学号/工号', trigger: 'blur'},
                        {validator:validateUserId, trigger:"blur"},
                    ],
                    phoneNumber: [
                        {required: false, message: '请输入手机号', trigger: 'blur'},
                        { pattern: /^1[3456789]\d{9}$/, message: "手机号码格式不正确", trigger: "blur" }
                    ],
                    email: [
                        {required: false,message: '请输入邮箱', trigger: 'blur'},
                        { pattern: /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/,message:"邮箱格式不正确",trigger:"blur"}
                    ],
                    statu: [
                        {required: true, message: '请选择状态', trigger: 'blur'}
                    ],
                },
                //上传文件用的

                //批量新增表单
                moreForm:{},
                //批量新增表单规则

                addVisible: false,
                addBatchVisible: false,
                editVisible: false,

                fileTemp:null,
                fileList: [],
            }
        },
        created() {
            this.getMemberList();
            this.getCollegeList();
        },
        methods:
            {
                //获取成员列表
                getMemberList() {
                    this.$axios.get('/sys/user/list').then(res => {
                        this.tableData = res.data.data
                    })
                },
                //获取学院列表
                getCollegeList() {
                    this.$axios.get('/sys/college/list').then(res => {
                        this.collegeData = res.data.data
                    })
                },
                //根据之前选择的院系id返回专业
                getMajorByCollege(college) {
                    console.log(college)
                    this.$axios.post('/sys/major/listByCollege?', {id: college}).then(res => {
                        // alert("选择了新的院系，现在在选择专业")
                        console.log(res.data.data)
                        this.majorData = res.data.data
                    })
                },
                //手动编辑
                editHandle(username) {
                    console.log(username)
                    this.$axios.post("/sys/user/info?", {username: username}).then(res => {
                      this.editForm = res.data.data;
                      //因为绑定的返回是id，但是显示的却是Name
                      this.editForm.major=res.data.data.majorName;
                      this.editVisible = true;
                    })
                },
                //手动删除
                delHandle(username) {
                    this.$axios.post("/sys/user/delete/" + username).then(res => {
                        console.log(res)
                        this.$message({
                            showClose: true,
                            message: '删除成功',
                            type: 'success',
                            onClose: () => {
                                this.getMemberList()
                                //刷新一下
                                window.location.reload();
                            }
                        });
                    })
                },
                //提交新增成员表单
                submitAddForm(formName) {
                    this.$refs[formName].validate((valid) => {
                        console.log(this.addForm)
                        if (valid) {
                            this.$axios.post('/sys/user/save', this.addForm)
                                .then(res => {
                                    console.log(res.data)
                                    this.resetAddForm(formName)
                                    this.$message({
                                        showClose: true,
                                        message: '恭喜你，操作成功',
                                        type: 'success',
                                        onClose: () => {
                                            this.getMemberList()
                                            location.reload();
                                        }
                                    });
                                })
                            this.addVisible = false;
                        } else {
                            console.log('error submit!');
                            return false;
                        }
                    });
                },
                //提交编辑成员表单
                submitEditForm(formName) {
                    this.$refs[formName].validate((valid) => {
                        if (valid) {
                            this.$axios.post('/sys/user/update/admin', this.editForm)
                                .then(res => {
                                    console.log(res.data)
                                    this.resetEditForm(formName)
                                    this.$message({
                                        showClose: true,
                                        message: '恭喜你，操作成功',
                                        type: 'success',
                                        onClose: () => {
                                            this.getMemberList();
                                        }
                                    });
                                })
                        } else {
                            console.log('error submit!');
                            return false;
                        }
                    });
                },
                // //批量提交
                // submitMoreForm(formName) {
                //   this.$refs[formName].validate((valid) => {
                //     if (valid) {
                //       this.$axios.post('/sys/user/save/batch' ,this.moreForm)
                //           .then(res => {
                //             console.log(res.data)
                //             this.resetForm(formName)
                //             this.$message({
                //               showClose: true,
                //               message: '恭喜你，操作成功',
                //               type: 'success',
                //               onClose: () => {
                //                 this.getMemberList()
                //               }
                //             });
                //           })
                //     } else {
                //       console.log('error submit!');
                //       return false;
                //     }
                //   });
                // },

                //重设表单
                resetAddForm(formName) {
                    this.$refs[formName].resetFields();
                    this.addForm = {}
                    this.addVisible = false
                },//重设表单
                resetEditForm(formName) {
                    this.$refs[formName].resetFields();
                    this.editForm = {}
                    this.editVisible = false
                },

                // 上传文件相关
                handleRemove(file, fileList) {
                    console.log(file, fileList);
                },
                handlePreview(file) {
                    console.log(file);
                },
                handleExceed(files, fileList) {
                    this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
                },
                beforeRemove(file, fileList) {
                    return this.$confirm(`确定移除 ${file.name}？`);
                },

                beforeUpload(file, fileList) {
                    this.fileTemp = file.raw
                    if (this.fileTemp) {
                        if ((this.fileTemp.type === '.csv') || (this.fileTemp.type === 'application/vnd.ms-excel')) {
                            this.importcsv(file.raw)
                        } else {
                            this.$message({
                                type: 'warning',
                                message: '附件格式错误，请删除后重新上传！'
                            })
                        }
                    } else {
                        this.$message({
                            type: 'warning',
                            message: '请上传附件！'
                        })
                    }
                    // let fileObj = item.file;
                    // const form = new FormData(); // FormData 对象
                    // form.append('sexcel', fileObj); // 文件对象  'upload'是后台接收的参数名
                    // this.$axios.post('/sys/user/save/batch',form, {headers :{'content-type':'application/json'}}).
                    // then((res) => {
                    //     if (res.status == 200) {
                    //         this.$message.success(res.data.msg);
                    //         this.upload = false;
                    //         this.$refs.upload.resetFileds();
                    //         this.getMemberList();
                    //
                    //     } else {
                    //         this.$message.error(res.data.msg);
                    //     }
                    // });
                    // let params= new FormData
                    // // let params = item.file
                    // console.log(item)
                    // // params.append("loginId", this.inf.userId);
                    // // params.append("projId", this.proproId);
                    // params.append("file", item);
                    // this.$axios({
                    //      method:'POST',
                    //      url:'/sys/user/save/batch',
                    //      data:qs.stringify(params),
                    //      // headers:{
                    //      //     'content-type':'multipart/form-data'
                    //      // }
                    //  }).then(res => {
                    //      console.log(res.data)
                    //  })
                    //      .catch(err => {
                    //          console.log(err)
                    //      })
                    // this.$refs[formName].validate((valid) => {
                    //     if (valid) {
                    //         this.$axios.post('/sys/user/save/batch?' + qs.stringify(this.moreForm))
                    //             .then(res => {
                    //                 console.log(res.data)
                    //                 this.$message({
                    //                     showClose: true,
                    //                     message: '恭喜你，操作成功',
                    //                     type: 'success',
                    //                     onClose: () => {
                    //                         this.getMemberList()
                    //                     }
                    //                 });
                    //             })
                    //     }
                    // });
                },
                importcsv: function(obj) {
                    // let obj=file.raw
                    let that = this//如果需要点击事件结束之后对DOM进行操作使用)_this.xx=xx进行操作
                    this.$papa.parse(obj.target.files[0], {
                        complete:function (results) {
                            console.log(results)//这个是csv文件的数据

                            // let data = []
                            for (let i = 1; i < results.data.length; i++) {
                                let obj=new FormData()
                                // obj.userRole =
                                //   obj.phoneNumber = results.data[i][1]
                                //   obj.identificationNumber = results.data[i][2]
                                //   obj.name = results.data[i][3]
                                //   obj.username = results.data[i][4]
                                //   obj.email = results.data[i][5]
                                //   obj.college = results.data[i][6]
                                //   obj.major = results.data[i][7]
                                obj.append("userRole",results.data[i][0])
                                obj.append("phoneNumber",results.data[i][1])
                                obj.append("identificationNumber",results.data[i][2])
                                obj.append("name",results.data[i][3])
                                obj.append("username",results.data[i][4])
                                obj.append("email",results.data[i][5])
                                obj.append("college",results.data[i][6])
                                obj.append("major",results.data[i][7])
                                obj.append("statu",results.data[i][8])

                                // console.log('2')
                                // console.log(obj)
                                that.$axios.post('/sys/user/bat',obj)
                            }
                            // data.splice(0, 1)//将数组第一位的表格名称去除
                            // let num = 0
                            // console.log('data', data)
                            /* _this.tableData = data//将数据放入要展示的表格中*/
                        }
                    });
                },
            }
    }
</script>

<style scoped>

</style>